<template>
	<div class="organization-tree-container">
		<div class="tree">
			<div class="tool-bar"><el-input :placeholder="`搜索${titleTxt}名字`" size="small" v-model.trim="filterText" clearable @clear="filterText=''"></el-input></div>
			<div class="content">
				<div class="content-container">
					<el-tree
						class="filter-tree"
						:data="treeData"
						show-checkbox
						default-expand-all
						node-key="id"
						:props="defaultProps"
						:filter-node-method="filterNode"
						@check="handleNodeClick"
						ref="tree"
						:empty-text="filterText===''?'暂无组织架构数据':'未找到相关数据'"
					></el-tree>
				</div>
			</div>
		</div>
		<div class="checkeds">
			<div class="content">
				<div class="content-container" v-if="checkIds && checkIds.length > 0">
					<template v-for="item of rightData">
						<div class="tree-top-level" :key="item.app_code" v-if="item.children.length > 0">
							<div class="row">
								<label>{{ item.name }}：</label>
							</div>
							<el-tag size="small" closable v-for="member in item.children" :key="member.id" @close="delTag(member)">{{ member.name }}</el-tag>
						</div>
					</template>
				</div>
				<div v-else class="empty-row">您未选择{{titleTxt}}，请在左侧勾选{{titleTxt}}</div>
			</div>
		</div>
	</div>
</template>

<script>
export default {
    props:{
        titleTxt:{
            require:true,
            type:String,
            default:'成员',
        }
    },
	data() {
		return {
			filterText: '', //关键字
			treeData: [], //后台json数据
			defaultProps: {
				//树绑定的值，对应json数据项
				children: 'children',
				label: 'name'
			},
			rightData: [], //右侧框的数据
			sameArr: [], //暂存用户id的数组
			allIds: [], //整个tree，所有老师的id
			checkIds: [] //左侧已勾选的老师的id
		};
	},
	created() {
		this.getData();
    },
    mounted () {
        
    },
	watch: {
		//搜索成员名字
		filterText(val) {
			this.$refs.tree.filter(val);
        },

	},
	computed: {
        // checkIdStr(){
        //     console.log(this.checkIds)
        // }
    },
	methods: {
		// 获取组织架构数据
		getData() {
			this.sameArr = [];
			let code = sessionStorage.getItem('CheckSchoolAppCode');
			let success = res => {
				this.treeData = this.searchTree(res.data);
                // 右侧数据结构：标题：教育局/学校-教师
                if(this.rightData.length===0){
                    this.rightData = this.treeData.map(x => {
                        return {
                            id: x.admin_id,
                            app_code: x.app_code,
                            name: x.name,
                            children: []
                        };
                    });
                }
			};

			this.$ajax({
				url: 'api/group/group_organization_user',
				method: 'get',
				params: {
					user_name: this.filterText,
					app_code: code ? code : '00000000000000000000000000000000'
				},
				func: { success: success }
			});
		},
		// 递归遍历
		// el-tree 绑定的节点node-key要求唯一，此处我绑定了节点的id值
		//由于组织架构中，老师可能绑定多个班级，所以出现多个节点是同一个老师，导致id不是唯一，el-tree报错
		//遍历初始数据，把id用rel_id存起来，出现id相同的节点，后面的节点都用id+父级id的来改一下，保证每个节点的id都不存在相同情况
		searchTree(data, pid) {
			const length = data.length;
			for (let i = 0; i < length; i++) {
				let item = data[i];
				item.rel_id = item.id; //添多一个字段存起id
				if (item.hasOwnProperty('user_number')) {
					//层层遍历，判断是否是最后一层：教师
					const flag = this.sameArr.includes(item.id); //如果之前存在这个id，则改一下这个id
					if (flag) {
						item.id = item.id + '_' + pid;
					} else {
						this.sameArr.push(item.id); //用一个数组存起id
					}
					this.allIds.push(item.id);
				} else {
					item['disabled'] = true; //只在教师层级显示checkbox框
				}
				// 如果还有下级，则继续遍历
				if (!is_empty(item.children)) {
					this.searchTree(item.children, item.id);
				}
			}
			return data;
		},
		// 输入框筛选
		filterNode(value, data) {
			if (!value) return true;
			return data.name.indexOf(value) !== -1;
        },
        // el-tree设置选中状态
        setChecked(ids) {
			this.$refs.tree.setCheckedKeys(ids);
		},
		// el-tree checkbox点击事件
		handleNodeClick(item) {
            // 判断是否有一个老师绑定多个班级的情况
            let checkIds = deep_clone(this.checkIds);
			if (checkIds.includes(item.id)) {
				this.checkIds = checkIds.filter(x => {
					return typeof x === 'string' && x.indexOf('_') > -1 ? x.split('_')[0] != item.rel_id : x != item.rel_id;
				});
			} else {
				let sameids = this.allIds.filter(x => {
					return typeof x === 'string' && x.indexOf('_') > -1 ? x.split('_')[0] == item.rel_id : x == item.rel_id;
				});
				this.checkIds = checkIds.concat(sameids);
            }
            this.setChecked(this.checkIds);//设置左侧的勾选状态

            //把勾选的人，放到右侧对应的组织架构下
            let rightData = deep_clone(this.rightData);
			let length = rightData.length;
			for (let i = 0; i < length; i++) {
				let elem = rightData[i];
				if (elem.app_code === item.user_app_code) {
					let flag = elem.children.every(x => x.rel_id != item.rel_id);
					if (flag) {
						elem.children.push(item);
					} else {
						elem.children = elem.children.filter(x => x.rel_id != item.rel_id);
					}
				}
            }
            this.rightData = rightData;
		},
		// 已选->tags删除选中
		delTag(item) {
            // 删除左侧选中
            let checkIds = deep_clone(this.checkIds);
			this.checkIds = checkIds.filter(x => {
				return typeof x === 'string' && x.indexOf('_') > -1 ? x.split('_')[0] != item.rel_id : x != item.rel_id;
			});
            this.setChecked(this.checkIds);
            //  删除右侧选中
            let rightData = deep_clone(this.rightData);
			let length = rightData.length;
			for (let i = 0; i < length; i++) {
				let elem = rightData[i];
				if (elem.app_code === item.user_app_code) {
					elem.children = elem.children.filter(x => x.rel_id != item.rel_id);
				}
            }
            this.rightData = rightData;
		},

	}
};
</script>
<style lang="scss">
.organization-tree-container {
	display: flex;
	min-height: 400px;
	.tool-bar {
		padding-bottom: 20px;
	}
	.content {
		height: 500px;
		border: 1px solid #dcdfe6;
		border-radius: 2px;
		overflow: scroll;
	}
	.tree {
		width: 45%;
		// .el-tree-node__expand-icon.is-leaf{
		//     color: #C0C4CC;
		//     &::before {
		//         content: "\e790";
		//     }
		// }
		.el-checkbox.is-disabled {
			display: none;
		}
		.content-container {
			padding: 10px;
		}
	}

	.checkeds {
		box-sizing: border-box;
		width: 55%;
		padding: 52px 0 0 24px;
		.content-container {
			padding: 16px;
		}
	}

	.empty-row {
		height: 100%;
		font-size: 12px;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #c0c4cc;
		background-color: #fff;
	}
	.tree-top-level {
		padding-bottom: 20px;
		.row {
			padding-bottom: 5px;
		}
		.el-tag {
			margin: 5px 10px 5px 0;
		}
	}
}
.el-tree__empty-block {
	height: 470px;
	.el-tree__empty-text {
		font-size: 12px;
		color: #c0c4cc;
	}
}
</style>
